<template>
  <div class="login-container">
    <!-- 头部Logo -->
    <div class="login-header">
      <div class="container">
        <a href="#" class="logo-title">KEXIO<span class="logo-subtitle">FORUM</span></a>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="login-main">
      <!-- 登录卡片 -->
      <div class="login-card">
      <h1 class="login-title">欢迎回来</h1>
      
      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        autocomplete="on"
        label-position="left"
      >
        <!-- 租户选择 -->
        <el-form-item v-if="tenantEnabled" prop="tenantId">
          <el-input
            v-model="loginForm.tenantId"
            placeholder="请选择租户"
          >
            <template #prefix>
              <i class="fas fa-building input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <!-- 账号/邮箱 -->
        <el-form-item prop="username">
          <label class="form-label">账号/邮箱</label>
          <el-input
            ref="usernameRef"
            v-model="loginForm.username"
            placeholder="请输入账号或邮箱"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
            clearable
            class="form-input"
          >
            <template #prefix>
              <i class="fas fa-user input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <div class="password-label">
            <label class="form-label">密码</label>
            <a href="#" class="forgot-password">忘记密码？</a>
          </div>
          <el-input
            :key="passwordType"
            ref="passwordRef"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.enter="handleLogin"
            class="form-input"
          >
            <template #prefix>
              <i class="fas fa-lock input-icon"></i>
            </template>
            <template #suffix>
              <span class="password-toggle" @click="showPwd">
                <i class="fas" :class="passwordType === 'password' ? 'fa-eye' : 'fa-eye-slash'"></i>
              </span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item v-if="captchaEnabled" prop="captcha">
          <el-input
            v-model="loginForm.captcha"
            placeholder="验证码"
            style="width: 60%"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <i class="fas fa-shield-halved input-icon"></i>
            </template>
          </el-input>
          <div style="width:35%;height:44px;float:right;">
            <img :src="captchaImage" style="width:100%;height:44px;border-radius:6px;border:1px solid #e4e7ed;" @click="getCaptcha" />
          </div>
        </el-form-item>

        <!-- 记住我 -->
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" class="remember-me">
            记住我（7天内免登录）
          </el-checkbox>
          <el-tooltip content="在公共设备上请勿勾选此选项" placement="top">
            <i class="el-icon-info-filled" style="margin-left: 8px; color: #909399; cursor: help;"></i>
          </el-tooltip>
        </el-form-item>
        
        <!-- 登录按钮 -->
        <el-button 
          :loading="loading" 
          type="primary" 
          class="login-button" 
          @click.prevent="handleLogin"
        >
          登录
        </el-button>
        
        <!-- 分隔线 -->
        <div class="divider">
          <span class="divider-text">其他方式登录</span>
        </div>
        
        <!-- 第三方登录 -->
        <div class="social-login">
          <el-button circle class="social-btn social-weibo" @click="handleSocialLogin('微博')" title="微博登录">
            <i class="fab fa-weibo"></i>
          </el-button>
          <el-button circle class="social-btn social-wechat" @click="handleSocialLogin('微信')" title="微信登录">
            <i class="fab fa-weixin"></i>
          </el-button>
          <el-button circle class="social-btn social-github" @click="handleSocialLogin('GitHub')" title="GitHub登录">
            <i class="fab fa-github"></i>
          </el-button>
          <el-button circle class="social-btn social-google" @click="handleSocialLogin('Google')" title="Google登录">
            <i class="fab fa-google"></i>
          </el-button>
        </div>
        
        <!-- 注册链接 -->
        <div class="register-link">
          <p>还没有账号？ <router-link to="/register" class="register-text">立即注册</router-link></p>
        </div>
        
        <!-- 登录提示（可通过环境变量控制显示） -->
        <div v-if="loginHintEnabled" class="tips">
          <span>请使用管理员分配的账号登录</span>
        </div>
      </el-form>
      </div>
    </div>

    <!-- 底部信息 -->
    <div class="login-footer">
      <div class="container">
        <p>© 2023 KEXIO FORUM. 保留所有权利。</p>
        <div class="footer-links">
          <a href="#" class="footer-link">关于我们</a>
          <a href="#" class="footer-link">使用条款</a>
          <a href="#" class="footer-link">隐私政策</a>
          <a href="#" class="footer-link">帮助中心</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { authApi } from '@/api/auth'
import { useAppStore } from '@/stores/app'
import { getRememberMe } from '@/config/storage'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

// 响应式数据
const savedTenantId = localStorage.getItem('kexio-tenant-id') || 'default'
const loginForm = reactive({
  username: '',
  password: '',
  tenantId: savedTenantId,
  captcha: '',
  captchaKey: '',
  rememberMe: getRememberMe()  // ✅ 从配置读取默认值
})

const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  tenantId: [{ required: true, trigger: 'change', message: '请选择租户' }],
  captcha: [{ required: true, trigger: 'blur', message: '请输入验证码' }]
}

const loading = ref(false)
const passwordType = ref('password')
const redirect = ref<string>()
const otherQuery = ref({})
const captchaImage = ref('')
const initLoading = ref(false)

// 引用
const loginFormRef = ref<InstanceType<typeof ElForm>>()
const usernameRef = ref<HTMLElement>()
const passwordRef = ref<HTMLElement>()

// 计算属性
const title = computed(() => appStore.systemTitle)
const tenantEnabled = computed(() => import.meta.env.VITE_TENANT_ENABLED === 'true')
const captchaEnabled = computed(() => import.meta.env.VITE_CAPTCHA_ENABLED === 'true')
const loginHintEnabled = computed(() => import.meta.env.VITE_LOGIN_HINT === 'true')
const showInit = computed(() => import.meta.env.MODE !== 'production')

// 方法
const showPwd = () => {
  if (passwordType.value === 'password') {
    passwordType.value = ''
  } else {
    passwordType.value = 'password'
  }
  // 聚焦到密码输入框
  if (passwordRef.value) {
    passwordRef.value.focus()
  }
}

const handleLogin = () => {
  loginFormRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      
      // 构建登录数据
      const loginData = {
        username: loginForm.username,
        password: loginForm.password,
        rememberMe: loginForm.rememberMe,  // ✅ 传递"记住我"选项
        ...(tenantEnabled.value && { tenantId: loginForm.tenantId }),
        ...(captchaEnabled.value && { 
          captcha: loginForm.captcha,  // ✅ 字段名与后端一致
          captchaKey: loginForm.captchaKey
        })
      }

      userStore.login(loginData)
        .then(async (loginResponse) => {
          console.log('🎉 登录流程完成，准备跳转', {
            token: loginResponse.accessToken?.substring(0, 8) + '...',
            userInfo: loginResponse.userInfo
          })
          
          ElMessage.success('登录成功')
          // 记住租户
          if (tenantEnabled.value) {
            localStorage.setItem('kexio-tenant-id', loginForm.tenantId)
          }
          
          // ✅ 直接跳转，router guard 会自动处理权限和路由加载
          router.push('/dashboard')
        })
        .catch((error) => {
          console.error('登录失败:', error)
          // 清空密码并聚焦
          loginForm.password = ''
          if (passwordRef.value) {
            passwordRef.value.focus()
          }
          // 刷新验证码（如果启用）
          if (captchaEnabled.value) {
            getCaptcha()
          }
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      console.log('表单验证失败')
    }
  })
}

const getCaptcha = () => {
  // 这里可以调用获取验证码的API
  // captchaImage.value = '/api/captcha?t=' + Date.now()
  // loginForm.captchaKey = 'captcha_key'
}

// 第三方登录处理函数
const handleSocialLogin = (platform: string) => {
  console.log(`使用 ${platform} 登录`)
  ElMessage.info(`正在跳转到${platform}登录页面...`)
  // TODO: 实际应用中，这里会跳转到对应的第三方登录页面
}

const getOtherQuery = (query: Record<string, any>) => {
  return Object.keys(query).reduce((acc, cur) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur]
    }
    return acc
  }, {} as Record<string, any>)
}

// 生命周期
onMounted(() => {
  const query = route.query
  if (query) {
    redirect.value = query.redirect as string
    otherQuery.value = getOtherQuery(query)
    
    // 如果从注册页面跳转过来，自动填充用户名
    if (query.username) {
      loginForm.username = query.username as string
      ElMessage.success('注册成功！请输入密码登录')
    }
  }
  
  // 或者从 localStorage 获取上次注册的用户名
  if (!loginForm.username) {
    const lastUsername = localStorage.getItem('kexio-last-username')
    if (lastUsername) {
      loginForm.username = lastUsername
      localStorage.removeItem('kexio-last-username') // 使用后清除
    }
  }

  // 获取验证码
  if (captchaEnabled.value) {
    getCaptcha()
  }
})
</script>

<style lang="scss" scoped>
// 所有样式已迁移到模块化样式文件中：
// - 登录页面样式 → src/styles/auth-module.scss
// - 密码切换样式 → src/styles/auth-module.scss

// 如有组件特定的样式需求，可在此添加
</style>
